package com.mini.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mini.admin.api.constant.AdminConstant;
import com.mini.admin.api.dto.MenuPageDTO;
import com.mini.admin.api.entity.SysMenu;
import com.mini.admin.api.vo.MenuTreeVO;
import com.mini.admin.mapper.SysMenuMapper;
import com.mini.admin.service.SysMenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    /**
     * 获取菜单的树形结构
     *
     * @return
     */
    @Override
    public List<MenuTreeVO> getMenuTree() {
        List<SysMenu> menuList = this.list(new LambdaQueryWrapper<SysMenu>().orderByAsc(SysMenu::getSort));
        return recurveMenuTree(AdminConstant.ROOT_MENU_ID, menuList);
    }

    /**
     * 递归获取树形结构，并获取简化的菜单
     * @return
     */
    private List<MenuTreeVO> recurveMenuTree(Long parentId, List<SysMenu> menuList) {
        ArrayList<MenuTreeVO> res = new ArrayList<>();

        Optional.ofNullable(menuList).orElseGet(ArrayList::new)
                .stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .forEach(menu -> {
                    MenuTreeVO menuTreeVO = new MenuTreeVO();
                    menuTreeVO.setId(menu.getId());
                    menuTreeVO.setMenuName(menu.getName());
                    menuTreeVO.setChildren(recurveMenuTree(menu.getId(), menuList));
                    res.add(menuTreeVO);
                });
        return res;
    }

    /**
     * 分页查询菜单
     */
    @Override
    public IPage<SysMenu> getMenuByPage(MenuPageDTO menuPageDTO) {
        Page<SysMenu> menuPage = new Page<>(menuPageDTO.getPageNum(), menuPageDTO.getPageSize());
        return this.page(menuPage);
    }
}




